<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 万通
 */
class WantongController extends PayController{
    protected $config;
    protected $class;
    protected $public;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));

        $this->public = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDo62/zwgNseqFDLsa1NbljX1zW
nyySb9lnLwpH/qfkkQ6QG5NZTm30D08hw3QmaNSe5f8eEdhagbfeEZszBb+Tveyn
fg1fMFjXjW/gWjDptZ2+DVSJPjCqxzS78WhGIMvYciZCLbLpF3jmJOKTLmcAhyqr
UvMZpI1BD+9W+CRUKwIDAQAB
-----END PUBLIC KEY-----";
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']) {
            //支付宝
            case 3:
            case 4:
                if($isMobile){
                    $payment_type = 23;
                }else{
                    $payment_type = 23;
                }
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $data = array();

        $encrypt_data = array(
            "uid"        =>    $this->config['mch_id'],
            "total_fee"  =>    $return['amount'],
            "subject"   =>    'tst',
            "order_no"   =>    $return['orderid'],
            "payment_type" =>  $payment_type,
            "description"=>    'zf',
            "return_url" =>    $return['callbackurl']
        );

        $encrypt_data = $this->str_jie($encrypt_data);
        $encrypt_data = $this->jencrypt($encrypt_data, $this->public);

        $data= [];
        $data['encrypt_data'] = $encrypt_data;
        //po("http://47.105.163.111/Payapi/Choose/classify?uid=".$this->config['mch_id'], $data);

        $res = curl("http://47.105.163.111/Payapi/Choose/classify?uid=".$this->config['mch_id'], httpstr($data));
        $res = json_decode($res, true);

        if(!$res || empty($res)){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $code = $res['data'];
        if(!$code){
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            //支付宝
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    function str_jie($arr){
        $str = "";
        foreach($arr as $k => $v){
            $str.=$k."=".$v."&";

        }
        $str = substr($str,0,strlen($str)-1);
        return $str;
    }

    private function get_md5($data){
        ksort($data);
        $str = httpstr($data);


    }

    function get_jtogether($request) {
        if(is_array($request)){
            ksort($request);
            $str = '';
            foreach($request as $k=>$v){
                $str .= $k.'='.$v.'&';
            }

            //$sign = $this->get_md5($request);
            // var_dump($sign);exit;
            $str = substr($str,0,strlen($str)-1);
            // var_dump($str);exit;
            //$str .= '&sign='.$sign;
            return $str;
        }else{
            // $data .= 'sign='.$sign;
            return $request;
        }

    }

    //rsa公钥加密----》针对接口方  base-64加密
    function jencrypt($request, $PUB_KEY) {
        // 先利用get_md5方法得出sign
        $data = $this->get_jtogether($request);
        // 判断字节
        // echo($data);exit;
        $len = strlen($data);
        // var_dump($data);exit;
        $str = '';
        $aa = '';
        $padding = OPENSSL_PKCS1_PADDING;
        if($len>=117){
            $zheng = intval($len/117);
            $yu  = -$len%117;
            for($i=0;$i<=$zheng-1;$i++){
                $str = substr($data, $i*117, 117);
                // 用公钥进行加密
                openssl_public_encrypt($str,$encrypted,$PUB_KEY,$padding);
                // 加密后的内容通常含有特殊字符，需要base64编码转换下
                // $encrypted = base64_encode($encrypted);
//          $aa .= $i;
                $aa .= $encrypted;
                // return $str;exit;
            }
            openssl_public_encrypt(substr($data,$yu),$yu_encrypted,$PUB_KEY,$padding);
            // 加密后的内容通常含有特殊字符，需要base64编码转换下
            $en_data = $aa.$yu_encrypted;
            // var_dump($en_data);exit;
            $rdata = base64_encode($en_data);
            // var_dump($rdata);exit;
            return $rdata;
        }else{
            // 用公钥进行加密
            openssl_public_encrypt($data,$encrypted,$PUB_KEY,$padding);
            // 加密后的内容通常含有特殊字符，需要base64编码转换下
            $encrypted = base64_encode($encrypted);
            return $encrypted;
        }

    }

    private function jdecrypt($rdata, $PUB_KEY) {
        // $de_str = '';
        $de_str = base64_decode($rdata);
        // var_dump($de_str);exit;
        $len = strlen($de_str);
        if($len>128){
            $str = '';
            $aa = '';
            $zheng = intval($len/128);
            $yu = -$len%128;
            for($i=0;$i<$zheng;$i++){
                $str = substr($de_str, $i*128, 128);
                openssl_public_decrypt($str, $dedata, $PUB_KEY);
                // var_dump($str);exit;
                $aa .= $dedata;
            }
            $arr = explode('&', $aa);
            $fin_arr = array();
            foreach($arr as $k=>$v){
                $in_arr = explode('=', $v);
                $fin_arr["$in_arr[0]"] = $in_arr[1];
            }
            return $arr;
        }else{
            // 加密后的内容通常含有特殊字符，需要base64编码转换下
            $data = base64_decode($rdata);
            // 用公钥进行解密
            openssl_public_decrypt($data,$encrypted,$PUB_KEY);
            return $encrypted;
        }

    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);


        $p = $origin = file_get_contents('php://input');

        //$p = "cdPDHj0JAjlqvAByQPlWLjJVvFwTB6ZoiioZCLAcJQJ92XXnxkXPHGA5JZCb0gJNIXGfBoU9AoZg79vJ5N8Uu6quLl5H2Mr60zMTYbWZz62Pg4gRJ93DqdjTJwTMiB9dZJ0HSMQd/y20cABDyXEV/DXW/a8iOu4sunDv5pNbJ4heYfC0m4YGfEXGhvQJ9MhmWgdNZCWuShFY5u/WHPB6JbnRs+O5I9TXoOblddAxap7qXaE0TuKBOseUndrbdGALIxRs2w5m42EltjzxWLgwzZ90Ns3nxEtiSz5rRSZKeUhqUlkcwZjN/h1QE2Cubd7mhCfP55vEsQf7Y6Iplk0Kcg==";

        $PUB_KEY = '';   //填入您的公钥
        $p = $this->jdecrypt($p, $this->public);  //获取公钥解密数据

        if(!$p || empty($p)){
            echo ''; exit;
        }

        $p = json_decode($p[0], true);
        if(!$p || empty($p)){
            echo ''; exit;
        }

        /*
         * Array
            (
                [order_no] => 2018121714313383324
                [price] => 10
                [status] => 1
                [sxf] => 60
                [time] => 1545028294
                [subject] => tst
                [paytime] => 1545028308
            )
         */

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['order_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
      /*  M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

        ));*/

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if($p['status'] != 1){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'SUCCESS');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}